package com.edu.bean;

import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import java.util.Set;

public class MyIOC {

    private Map<Object,Object> map = new HashMap<>();

    public MyIOC(String path){
        Properties pro = new Properties();
        InputStream ins = MyIOC.class.getClassLoader().getResourceAsStream(path);
        if(ins == null){
            System.out.println("配置文件不存在");
            return;
        }
        try {
            pro.load(ins);
            Set<String> keys = pro.stringPropertyNames();
            for (String key : keys) {
                String className = pro.getProperty(key);
                Class clazz = Class.forName(className);
                Constructor c1 = clazz.getDeclaredConstructor();
                c1.setAccessible(true);
                Object o = c1.newInstance();
                map.put(key,o);
            }
        } catch (IOException e) {
            System.out.println("配置文件无法正常读取");
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            System.out.println("该类文件不存在");
            e.printStackTrace();
        } catch (NoSuchMethodException e) {
            System.out.println("没有无参数构造");
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
    }


    public Object getBean(String beanId){
        return map.get(beanId);
    }

    public Object getBean(Class clazz){
        Set<Object> keys = map.keySet();
        for (Object key : keys) {
            Object o = map.get(key);
            if(o.getClass() == clazz){
                return o;
            }
        }
        return null;
    }

    @Override
    public String toString() {
        return "MyIOC{" +
                "map=" + map +
                '}';
    }
}
